namespace FilterDemo
{
	using System;
	using System.Collections.Generic;
	using System.ComponentModel;
	using System.Threading;

	using PugLib.Extensions;
	using PugLib.Filters;
	using PugLib.TestCollateral;
	using PugLib.UI;

	public sealed partial class FilterDemoView : PugForm
	{
		private FilterDemoController _controller;

		public FilterDemoView()
		{
			InitializeComponent();
		}

		private void InitializeFormData(object state)
		{
			FillGrid();
		}

		private void LaunchClick(object sender, EventArgs e)
		{
			_controller.LaunchFilterBuilder();
		}

		internal void UpdateFilterView(List<SearchFilter> filters)
		{
			lbCurrentFilters.Items.Clear();

			filters.ForEach(f => lbCurrentFilters.Items.Add(f));
		}

		internal void UpdateSearchingView()
		{
			lblItemCount.Text = "Searching...";

			UpdateResults();
		}

		internal void UpdateResults()
		{
			ThreadPool.QueueUserWorkItem(UpdateResults);
		}

		private void UpdateResults(object state)
		{
			IList<Computer> filteredItems = _controller.GetFilteredItems();
			ModifyControls(filteredItems);
		}

		private void ModifyControls(IList<Computer> filteredItems)
		{
			dgvItems.BeginInvokeIfRequired(UpdateDataGridView, filteredItems);
			lblItemCount.BeginInvokeIfRequired(UpdateItemCount, filteredItems.Count);
		}

		private void UpdateItemCount(int count)
		{
			lblItemCount.Text = "Items in view: " + count;
		}

		private void UpdateDataGridView(IList<Computer> filteredItems)
		{
			dgvItems.DataSource = filteredItems;
		}

		/// <summary>
		/// Dummy test data
		/// </summary>
		private void FillGrid()
		{
			_controller.GenerateTestState();

			dgvItems.BeginInvokeIfRequired(BindGrid, _controller.DataForDemo);
			lblItemCount.BeginInvokeIfRequired(UpdateStatus, "Items in view: " + _controller.DataForDemo.Count);
			progress.BeginInvokeIfRequired(StopProgress);
		}

		private void StopProgress()
		{
			progress.Stop();
		}

		private void UpdateStatus(string statusMessage)
		{
			lblItemCount.Text = statusMessage;
		}

		private void BindGrid(BindingList<Computer> data)
		{
			dgvItems.DataSource = data;
		}

		private void dialogTest_Click(object sender, EventArgs e)
		{
			FilterDemoController.ShowTestDialogs();
		}

		private void DemoShown(object sender, EventArgs e)
		{
			_controller = new FilterDemoController(this);
			progress.Start();
			ThreadPool.QueueUserWorkItem(InitializeFormData, this);
		}

		private void btnCustomDialogTest_Click(object sender, EventArgs e)
		{
			FilterDemoController.ShowCustomDialogTest();
		}

		private void btnCustomDialogExtraTest_Click(object sender, EventArgs e)
		{
			FilterDemoController.ShowCustomDialogExtraTest();
		}

		private void btnTaskDialogTest_Click(object sender, EventArgs e)
		{
			FilterDemoController.ShowTaskDialogTest();
		}
	}
}